12. Template Classes

12 Template Class

1- Copy this code to your editor and save it on your VM Desktop as RoboticTemplate.cpp:

#include <iostream>
#include <string.h>
using namespace std;

template <class data_type>
class Robot {
    private:
        data_type speed;
    public:
        Robot(data_type sp):speed(sp){/*speed=sp*/}

          data_type GetSpeed()
          {
              return speed;
          }
};

int main() 
{
   Robot <int> robot1(100);
   Robot <float> robot2(50.5);
   Robot <string> robot3("ten");

   cout << "Robot1 speed : " << robot1.GetSpeed() <<endl;
   cout << "Robot2 speed : " << robot2.GetSpeed() <<endl;
   cout << "Robot2 speed : " << robot3.GetSpeed() <<endl;

   return 0;
}                                                               

2- Then, navigate to Desktop:

$ cd Desktop

3- While in Desktop, compile the code:

$ g++ RoboticTemplate.cpp -o app

4- Now, run your program:

$ ./app

5- After running this program, each object should display its speed with the proper data type :